package com.it.day3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName: SaleTicketDemo
 * Description: 演示非公平和公平锁
 *
 * @Author: csx
 * @Create: 2025/5/9 - 10:40
 * @version: v1.0
 */
public class SaleTicketDemo {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(() -> { for (int i = 0; i < 55; i++) ticket.sale(); }, "t1").start();
        new Thread(() -> { for (int i = 0; i < 55; i++) ticket.sale(); }, "t2").start();
        new Thread(() -> { for (int i = 0; i < 55; i++) ticket.sale(); }, "t3").start();
        new Thread(() -> { for (int i = 0; i < 55; i++) ticket.sale(); }, "t4").start();
        new Thread(() -> { for (int i = 0; i < 55; i++) ticket.sale(); }, "t5").start();
    }
}

class Ticket{
    private int sumber = 50;

    private Lock lock = new ReentrantLock(true);    //默认是非公平，加true为公平

    public void sale(){
        lock.lock();
        try {
            if (sumber > 0){
                System.out.println(Thread.currentThread().getName() + "\t卖出第 " + (sumber--) + " 张票 \t"+"还剩："+sumber);
            }
        } finally {
            lock.unlock();
        }
    }
}



























